package sy.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUpload {
	public static ResultJson fileUpload(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		StringBuffer imgUrl = new StringBuffer();
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
		/**
		 * 检查form中是否有enctype="multipart/form-data"
		 */
		if (multipartResolver.isMultipart(request)) {
			/**
			 * 将request变成多部分request
			 */
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			/**
			 * 获取multiRequest 中所有的文件名
			 */
			Iterator iter = multiRequest.getFileNames();
			//RemoteFileUpload sftp = new RemoteFileUpload("zhuanye", "Zhwy123", "192.168.200.116", 22);  
			while (iter.hasNext()) {
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if (file!=null) {
					/**
					 * 保存在resource/appImages路径下
					 */
					String path = request.getSession().getServletContext().getRealPath("/") + "/resource/appImages/";
					/**
					 * 1.String realPath = request.getSession().getServletContext().getRealPath("/resource/appImages/") ;
					 * 2.String realPath = request.getSession().getServletContext().getRealPath("/") + "/resource/appImages/";
					 * 1和2的写法得到的结果是不一样的，前者不能进入appImages路径，只能到resource
					 */
					File fileItem = new File(path);
					if (!fileItem.exists()) {
						fileItem.mkdir();
					}
					String realName = path + file.getOriginalFilename();
					try {
						/**
						 * 上传文件到指定位置
						 * 先上传到本地服务器，再上传到服务器指定的服务器目录
						 */
						File file1 = new File(realName);
						String realfileName = file.getOriginalFilename();
						String rename = path + file.getOriginalFilename();
						if(file1.exists()){
							int radomInt = new Random().nextInt(999999);
							String fileName = String.valueOf(radomInt);
							do{
								radomInt = new Random().nextInt(999999);
							}while(fileName.length()<6);
							
							realfileName = System.currentTimeMillis() + fileName + "." + 
							    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);//重命名照片名称：path+当前时间戳+随机6位数
							rename = path + realfileName;
						}
						
						file1.renameTo(new File(rename));
						file.transferTo(file1);
						
						
				        /*sftp.login();  
				        InputStream is = new FileInputStream(file1);  
				        sftp.upload("/opt/apache-tomcat-8.5.20/webapps/appImagesFloder", file.getOriginalFilename(), is);  */
						
						resultJson.setState(true);
						imgUrl.append("resource/appImages/"+realfileName+",");
						/**
						 * flag = 0表示上传成功，1表示失败，2表示没有文件上传。
						 * 报事接口要根据该值来判断有没有文件上传/文件上传的结果
						 */
						resultJson.setFlag("0");
						resultJson.setMessage(imgUrl.toString());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						resultJson.setState(false);
						/**
						 * 上传失败
						 */
						resultJson.setFlag("1");
						e.printStackTrace();
					} 
				}
			}
			//sftp.logout();  
			/**
			 * 有文件上传,文件名去掉最后一个逗号
			 */
			if (imgUrl.toString().length()>0){
				resultJson.setMessage(imgUrl.deleteCharAt(imgUrl.length()-1).toString());
			}
		} else {
			resultJson.setState(false);
			/**
			 * 没有文件可上传
			 */
			resultJson.setFlag("2");
		}
		return resultJson;
	}
	
	public static void main(String[] args){
/*		int radomInt = new Random().nextInt(999999);
		String fileName = String.valueOf(radomInt);
		do{
			radomInt = new Random().nextInt(999999);
		}while(fileName.length()<6);
		System.out.println(System.currentTimeMillis()+fileName);*/
	}
}
